<template>
  <section>
    <div class="filter-container">
        <common-input @keyup.enter.native="handleFilter" class="w200 ml10" placeholder="佣金规则名称" v-model="listQuery.keyword" />
        <el-button size="mini" class="ml10" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
        <el-button size="mini" class="ml10" @click="handleCreate" type="primary" icon="el-icon-plus">新增</el-button>
    </div>
    
    <el-table ref="dataTable" :height="tableHeight" :data="list"
                        @sort-change="tblSort"
                style="width: 100%">
            <el-table-column align="left" label="佣金规则名称">
                <template slot-scope="scope">
                    <span>{{scope.row.name}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="佣金类型">
                <template slot-scope="scope">
                    <span>{{scope.row.typeTxt}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="发展关系">
                <template slot-scope="scope">
                    <span>{{scope.row.developRelationTxt}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="订单类型">
                <template slot-scope="scope">
                    <span>{{scope.row.orderTypeTxt}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="佣金人员类型">
                <template slot-scope="scope">
                    <span>{{scope.row.userTypeTxt}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="分佣来源">
                <template slot-scope="scope">
                    <span>{{scope.row.source== 1?'订单':'利润'}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="分佣比例">
                <template slot-scope="scope">
                    <span>{{scope.row.percent}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="佣金形式">
                <template slot-scope="scope">
                    <span>{{scope.row.form== 1?'现金':'红包' }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" 
                    fixed="right" v-if="!isSelect">
                <template slot-scope="scope">
                    <span>
                        <el-dropdown class="ml10">
                        <el-button

                                type="text">
                            更多<i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item @click.native="handleUpdate(scope.row)">编辑</el-dropdown-item>
                            <el-dropdown-item  @click.native="handleDelete(scope.row)">删除</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                    </span>
                </template>
            </el-table-column>
    </el-table>
        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNum" :page-sizes="[20,30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
        </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="900px">
        <!-- <el-form :model="form" :rules="rules" ref="form" label-width="150px">
            <el-form-item label="佣金规则名称" prop="name">
                <common-input v-model="form.name" placeholder="请输入佣金规则名称" maxlength="10" />
            </el-form-item>
            <el-form-item label="本级比例" prop="percent">
                <el-input type="number" size="mini" v-model="form.percent" />
            </el-form-item>
            <el-form-item label="上级比例" prop="percent2">
                <el-input type="number" size="mini" v-model="form.percent2" />
            </el-form-item>
            <el-form-item label="上上级比例" prop="percent3">
                <el-input type="number" size="mini" v-model="form.percent3" />
            </el-form-item>
            <el-form-item label="上上上级比例" prop="percent4">
                <el-input type="number" size="mini" v-model="form.percent4" />
            </el-form-item>
            <el-form-item label="上上上上级比例" prop="percent5">
                <el-input type="number" size="mini" v-model="form.percent5" />
            </el-form-item>
            <el-form-item label="上上上上上级比例" prop="percent6">
                <el-input type="number" size="mini" v-model="form.percent6" />
            </el-form-item>
        </el-form> -->
        <el-form :model="forms" :rules="rules" ref="form" label-width="150px">
            <el-form-item label="佣金规则名称" prop="name">
                <common-input v-model="forms.name" placeholder="请输入佣金规则名称" maxlength="10" />
            </el-form-item>
            <el-form-item label="佣金类型" prop="type">
                <!-- <el-input type="number" size="mini" v-model="forms.type" /> -->
                <el-select v-model="forms.type" placeholder="请选择" @change="changeRole">
                    <el-option v-for="(item,index) in sList"  :key="index" :label="item.label" :value="item.id">
                    </el-option>
                  </el-select>
            </el-form-item>
            <el-form-item label="发展关系" prop="developRelation">
                <!-- <el-input type="number" size="mini" v-model="forms.developRelation" /> -->
                <el-select v-model="forms.developRelation" placeholder="请选择" @change="changeRole">
                    <el-option v-for="(item,index) in sList03"  :key="index" :label="item.label" :value="item.id">
                    </el-option>
                  </el-select>
            </el-form-item>
            <el-form-item label="订单类型" prop="orderType">
                <!-- <el-input type="number" size="mini" v-model="forms.orderType" /> -->
                <el-select v-model="forms.orderType" placeholder="请选择" @change="changeRole">
                    <el-option v-for="(item,index) in sList02" :key="index" :label="item.label" :value="item.id">
                    </el-option>
                  </el-select>
            </el-form-item>
            <el-form-item label="佣金人员类型" prop="userType">
                <el-select v-model="forms.userType" placeholder="请选择" @change="changeRole">
                    <el-option v-for="(item,index) in sList04" :key="index" :label="item.label" :value="item.id">
                    </el-option>
                  </el-select>
                <!-- <el-input type="number" size="mini" v-model="forms.userType" /> -->
            </el-form-item>
            <el-form-item label="分佣来源" prop="source">
                <el-radio-group v-model="forms.source">
                    <el-radio :label="1">订单</el-radio>
                    <el-radio :label="2">利润</el-radio>
                  </el-radio-group>
                <!-- <el-input type="number" size="mini" v-model="forms.source" /> -->
            </el-form-item>
            <el-form-item label="分佣比例" prop="percent">
                <el-input type="number" size="mini" v-model="forms.percent" />
            </el-form-item>
            <el-form-item label="佣金形式" prop="form">
                <el-radio-group v-model="forms.form">
                    <el-radio :label="1">现金</el-radio>
                    <el-radio :label="2">红包</el-radio>
                  </el-radio-group>
                <!-- <el-input type="number" size="mini" v-model="form.form" /> -->
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button size="mini" @click="dialogFormVisible=false">取消</el-button>
            <el-button size="mini" type="primary" @click="create('form')">确定</el-button>
            <!-- <el-button size="mini" v-else type="primary" @click="update('form')">确定</el-button> -->
        </div>
    </el-dialog>

  </section>
</template>

<script>
    import {
        isIntegerNotMust
    } from '../../utils/validator'
    import {
        sale_rule_list,
        sale_rule_detail,
        sale_rule_save,
        sale_rule_delete,
        sale_rule_update
    } from '../../api/member';
    import Viewer from 'viewerjs';
    import 'viewerjs/dist/viewer.css';
    export default {
        components: {
        },
        props: {
            formData: Object
        },

// RETAIL_GOODS
        data() {
            return {
                sList: [
                    {id:1,label: '入驻费', value: 'ENTRY_FEE'},
                    {id:2,label: '年费', value: 'ANNUAL_FEE'},
                    {id:3,label: '用户充值红包', value: 'RECHARGE_RED_PACKET'},
                    {id:4,label: '小店买单', value: 'SHOP_BUY_ORDER'},
                    {id:5,label: '买小店商品', value: 'BUY_SHOP_GOODS'},
                    {id:6,label: '平台商品', value: 'PLATFORM_GOODS'},
                    {id:7,label: '手动调整', value: 'MANUAL_ADJUSTMENT'},
                    {id:8,label: '零售商品', value: 'RETAIL_GOODS'}
                ],
                
                sList02: [
                    {id:1,label: '区域内特通自拓小店', value: 'REGION_TE_TONG_SELF_TO_SHOP'},
                    {id:2,label: '特通自拓小店', value: 'TE_TONG_SELF_TO_SHOP'},
                    {id:3,label: '区域自拓小店', value: 'REGION_SELF_TO_SHOP'},
                    {id:4,label: '区域自拓会员', value: 'REGION_SELF_TO_MEMBER'},
                    {id:5,label: '特通自拓会员', value: 'TE_TONG_SELF_TO_MEMBER'}
                ],
                
                sList03: [
                    {id:1,label: '首年入驻费', value: 'FIRST_YEAR_ENTRY_FEE'},
                    {id:2,label: '次年年费', value: 'RENEWAL'},
                    {id:3,label: '充值红包', value: 'RECHARGE_RED_PACKET'},
                    {id:4,label: '小店买单', value: 'SHOP_BUY_ORDER'},
                    {id:5,label: '买小店商品', value: 'BUY_SHOP_GOODS'},
                    {id:6,label: '平台商品', value: 'PLATFORM_GOODS'},
                    {id:7,label: '货物分配', value: 'DISTRIBUTION_OF_GOODS'}
                ],
                sList04: [
                    {id:1,label: '区域合伙人', value: 'AREA_PARTNER'},
                    {id:2,label: '特通合伙人', value: 'TE_TONG_PARTNER'},
                    {id:3,label: '小店', value: 'SHOP'},
                    {id:4,label: '用户', value: 'USER'}
                ],
                rules: {
                    name: [
                        {
                            required: true,
                            message: '请输入佣金规则名称',
                            trigger: 'blur'
                        }
                    ],
                },
                form: {
                    id: undefined,
                    name: undefined,
                    percent: undefined,
                    percent2: undefined,
                    percent3: undefined,
                    percent4: undefined,
                    percent5: undefined,
                    percent6: undefined,
                },
                forms: {
                    id: undefined,
                    name: undefined,
                    type: undefined,
                    developRelation: undefined,
                    orderType: undefined,
                    userType: undefined,
                    source: undefined,
                    percent: undefined,
                    form: undefined,
                },
                dialogStatus: '',
                dialogFormVisible: false,
                textMap: {
                    update: '编辑佣金规则',
                    create: '新增佣金规则'
                },

                isSelect: false,
                viewerId: null,
                orderLoading: false,
                tableHeight: 200,
                list: null,
                listLoading: true,
                listQuery: {
                    pageNum: this.$route.query.pageNum || 1,
                    pageSize: this.$route.query.pageSize || 20,
                    keyword: this.$route.query.keyword || '',
                    
                },
                total: null,
                activeName: '1',
                currentId: 0,
                checkLoading: false,
            }
        },
        watch: {
            formData: {
                immediate: true,
                handler (val) {
                    this.isSelect = val.is_select;

                    // console.log(val)
                }
            }
        },
        mounted() {
            const that = this

            window.onresize = () => {

                return (() => {

                    that._getTableHeight()

                })()
            }
        },
        created() {
            this._getTableHeight();
            this.getList();
        },
        methods: {
            okSelectProduct(result) {
                this.dialogProductVisible = false;
                if(!this.form.items) {
                    this.form.items = [];
                }
                // console.log("idx: " + this.selectedIdx)
                if(typeof this.selectedIdx != "undefined") {
                    this.form.items[this.selectedIdx].title = result.title;
                    this.form.items[this.selectedIdx].attribute = result.attribute;
                    this.form.items[this.selectedIdx].productId = result.productId;
                    this.form.items[this.selectedIdx].skuId = result.skuId;
                    this.form.items[this.selectedIdx].price = result.price;
                    this.form.items[this.selectedIdx].skuInventory = result.skuInventory;
                } else {
                    this.form.items.push(result);
                }
                console.log(result)
                // product_add_to_page(
                //     {
                //         pageId: this.pageId,
                //         ids: ids
                //     }
                // ).then((res)=>{
                //     this.$message.success("商品已加入专区");
                //     this.getList();
                //     this.dialogProductVisible = false;
                // }).catch((err)=>{

                // })
                // console.log(ids)
            },
            addItem(idx) {
                this.selectedIdx = idx;
                this.dialogProductVisible = true;
            },
            removeItem(idx) {
                this.$confirm('确定删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        let final_items = [];
                        this.form.items.forEach((item, i)=>{
                            if(i != idx) {
                                final_items.push(item);
                            }
                        })

                        this.form.items = final_items;
                    }).catch(()=>{});
            },
            handleCreate() {
                this.resetTemp();
                this.dialogStatus = 'create';
                this.dialogFormVisible = true;
            },
            create(formName) {
                console.log(this.forms)
                this.$refs['form'].validate(valid => {
                if (valid) {
                // if (this.formDataAdd.serviceManager) {

                //     this.formDataAdd.memberId ? '' : this.$message.error('请输入绑定会员id')
                //     return false
                // }
                if (this.forms.id) {
                    sale_rule_update(this.forms).then(res => {
                    console.log(res)
                    if (res.code === 200) {
                        this.$message.success('修改成功')

                        this.dialogFormVisible = false
                        this.getList()
                    } else {
                        this.$message.error(res.message)
                    }
                    })
                } else {
                    // if (this.forms.password.length < 8) {
                    // this.$message.error('密码至少为8个字符')
                    // return false
                    // }
                    sale_rule_save(this.forms).then(res => {
                    console.log(res)
                    if (res.code === 200) {
                        this.$message.success('创建成功')
                        this.getList()
                        this.dialogFormVisible = false
                    } else {
                        this.$message.error(res.message)
                    }
                    })
                }
                }
            })
                // const set = this.$refs;
                // set[formName].validate(valid => {
                //     if (valid) {
                //         if(!this.form.orderNum) {
                //             this.form.orderNum = 0;
                //         }
                //         sale_rule_save(this.form)
                //             .then(() => {
                //                 this.dialogFormVisible = false;
                //                 this.getList();
                //                 this.$message.success("佣金规则创建成功");
                //             })
                //     } else {
                //         return false;
                //     }
                // });
            },
            update(formName) {
                const set = this.$refs;
                set[formName].validate(valid => {
                    if (valid) {
                        if(!this.form.orderNum) {
                            this.form.orderNum = 0;
                        }

                        sale_rule_save(this.form).then(() => {
                            this.dialogFormVisible = false;
                            this.getList();
                            this.$message.success("佣金规则更新成功");
                        });
                    } else {
                        return false;
                    }
                });
            },
            resetTemp() {
                this.form = {
                    id: undefined,
                    name: undefined,
                    percent: undefined,
                    percent2: undefined,
                    percent3: undefined,
                    percent4: undefined,
                    percent5: undefined,
                    percent6: undefined,
                };
            },
            _getTableHeight() {
                this.tableHeight = window.innerHeight - 250
            },
            txtBakc(val){
                return val
   
            },
            getList() {
                this.listLoading = true;
                sale_rule_list(this.listQuery).then(response => {
                    this.list = response.data.list;

                    this.list.forEach(item=>{
                       
                        item.typeTxt = this.sList.find(i=>i.id == item.type)
                        item.orderTypeTxt = this.sList03.find(i=>i.id == item.orderType)
                        item.developRelationTxt = this.sList02.find(i=>i.id == item.developRelation)
                        item.userTypeTxt = this.sList04.find(i=>i.id == item.userType)
                        item.typeTxt?item.typeTxt=item.typeTxt.label:item.typeTxt='--'
                        item.orderTypeTxt?item.orderTypeTxt=item.orderTypeTxt.label:item.orderTypeTxt='--'
                        item.developRelationTxt?item.developRelationTxt=item.developRelationTxt.label:item.developRelationTxt='--'
                        item.userTypeTxt?item.userTypeTxt=item.userTypeTxt.label:item.userTypeTxt='--'
                        })
                        console.log(this.list)
                    this.total = response.data.total;
                    this.listLoading = false;
                    
                })
            },
            viewPic(row) {
                if(row.imgUrls) {
                    let all_pic = row.imgUrls.split(",");
                    $("#pic_viewer").html("");
                    if(all_pic && all_pic.length > 0) {
                        all_pic.forEach((item, idx)=>{
                            var str  = '<li style="width:100%;">';
                            str += '<img rel-src="' + item + '" src="' + item + '">';
                            str += '</li>';
                            $("#pic_viewer").append(str);
                        })
                    }
                    this.viewerId && this.viewerId.destroy()
                    this.viewerId = new Viewer(document.getElementById('pic_viewer'));
                    $('#pic_viewer').find("img").eq(0).trigger("click")
                }
            },
            changeRole(){

            },
            handleFilter() {
                this.listQuery.pageNum = 1;
                this.getList();
            },
            handleSizeChange(val) {
                this.listQuery.pageSize = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.listQuery.pageNum = val;
                this.getList();
            },
            handleUpdate(row) {
                
                // sale_rule_detail(row.id)
                //     .then(response => {
                        this.forms = row;
                        console.log(this.forms)
                        this.dialogFormVisible = true;
                        // this.dialogStatus = 'update';
                    // });
            },
            handleDelete(row) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        sale_rule_delete(row.id)
                            .then(() => {
                                this.$message.success("佣金规则删除成功");
                                this.getList();
                            });
                    }).catch(()=>{});
            },
            dialogClose() {
                this.$refs.form.resetFields();
            },
            tblSort(d) {
                this.listQuery.orderCol = d.prop;
                this.listQuery.orderAsc = d.order;

                this.handleFilter();
            },
            selectChange(selection) {
                this.ids = [];
                if(selection && selection.length > 0) {
                    selection.forEach((item)=>{
                        this.ids.push(item.id)
                    })
                }
                // console.log(this.ids)
            },
            clear() {
                this.$refs.dataTable.clearSelection();
            },
            select() {
                this.$emit('okSelect', this.ids);
            }
        }
    };
</script>
<style lang="scss" scoped>
</style>
